<?php

/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2016/10/29
 * Time: 16:56
 */

namespace Aoe\Intent\User;


use Aoe\Intent\Request\Http;
use Aoe\Util\Swap\Only;

/**
 * # 当前登录用户信息
 *
 * @property int      id
 * @property string   name        用户名
 * @property string   label       昵称
 * @property int[]    powers     权限数组 { resource => powers }
 * @property string   home      主页
 * @property bool     super     超级管理员
 *
 */
class User extends Only
{
    /**
     * 索引-字符串-SESSION_KEY
     */
    const string SESSION_KEY = '__aoe_user_session__';
    /**
     * 索引-字符串-ID
     */
    const string KEY_ID     = 'id';
    /**
     * 索引-字符串-用户名
     */
    const string KEY_NAME   = 'name';
    /**
     * 索引-字符串-用户名
     */
    const string KEY_NICK   = 'label';
    /**
     * 索引-数组-资源的权限值
     */
    const string KEY_POWERS = 'powers';
    /**
     * 索引-布尔-是否超级管理员
     */
    const string KEY_SUPER  = 'super';
    
    /**
     * @var bool 已登录
     */
    protected(set) bool $logged = false {
        get {
            return $this->logged;
        }
    }

    public function __construct(protected Http $http)
    {
        $information = $this->http->session->get(self::SESSION_KEY);
        if ($information) $this->_try_login($information);
    }

    public function login(array $information): void
    {
        $this->_try_login($information);
        $this->http->session->set(self::SESSION_KEY, $this->attributes);
    }

    public function logout(): void
    {
        $this->http->session->del(self::SESSION_KEY);
        $this->attributes = [];
        $this->logged     = false;
    }
    
    /** @noinspection PhpUnused */
    public static function getInnerSuper(): array
    {
        return [
            User::KEY_NAME  => 'admin',
            User::KEY_NICK  => '超级管理员',
            User::KEY_ID    => 1,
            User::KEY_SUPER => true,
        ];
    }
    
    private function _try_login(array $information): void
    {
        $this->logged     = true;
        $this->attributes = $information;
    }
    
    public function isAdministrator(): bool
    {
        // TODO  深化超级管理员判断
        return $this->super;
    }
    
    
    public function hasPower(string $resource, int $power, int $id): bool
    {
        return $this->hasAdminPower($resource, $power) || $this->hasSelfPower($resource, $power, $id);
    }
    
    public function hasSelfPower(string $resource, int $power, int $id): bool
    {
        return (($this->powers[$resource] ?? 0) & $power) && $this->id === $id;
    }
    
    public function hasAdminPower(string $resource, int $power): bool
    {
        return ($this->powers[$resource] ?? 0) & Power::ADMIN & $power;
    }
    
    /**
     * 不检查ID
     *
     * @param string $resource
     * @param int    $power
     *
     * @return bool
     */
    public function hasNormalPower(string $resource, int $power): bool
    {
        return ($this->powers[$resource] ?? 0) & $power;
    }
}